package com.xsh.opensltest;

import android.content.Context;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class FileUtils {

    public static boolean cleanCache(Context ctx,File dir)
    {
        return clearDirectory(ctx, dir);
    }

    public static boolean clearDirectory(Context context, File dir) {
        if (!dir.exists()) {
            return true; // 不存在就认为已经清空了
        }

        if (!dir.isDirectory()) {
            return false; // 不是目录不能清空
        }

        File[] files = dir.listFiles();
        if (files == null) {
            return true; // 空目录无需处理
        }

        for (File file : files) {
            if (file.isDirectory()) {
                deleteRecursive(file); // 递归删除文件夹
            } else {
                if (!file.delete()) {
                    // 可选：打印日志
                    // Log.e("FileUtils", "无法删除文件：" + file.getAbsolutePath());
                    return false;
                }
            }
        }

        return true;
    }
    /**
     * 递归删除文件夹及其内容
     */
    private static boolean deleteRecursive(File fileOrDir) {
        if (fileOrDir == null || !fileOrDir.exists()) {
            return true;
        }

        if (fileOrDir.isDirectory()) {
            File[] children = fileOrDir.listFiles();
            if (children != null) {
                for (File child : children) {
                    deleteRecursive(child);
                }
            }
        }

        return fileOrDir.delete();
    }
    /**
     * 复制文件
     * @param srcFile  源文件路径
     * @param destFile 目标文件路径
     * @return 是否复制成功
     */
    public static boolean copyFile(String srcFile, String destFile) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            File dest = new File(destFile);
            // 如果目标目录不存在则创建
            File parent = dest.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }

            inputStream = new FileInputStream(srcFile);
            outputStream = new FileOutputStream(destFile);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }

            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 2025/6/3 复制到cache目录的高版本安卓方法
    public static void copyInputStreamToFile(InputStream in, File file) throws IOException
    {
        OutputStream out = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int read;

        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }

        in.close();
        out.close();
    }

    /*public void unzip(File zipFilePath,String destDir) throws Exception
    {
        try (ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFilePath)))) {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {
                String filePath = destDir + File.separator + entry.getName();
                if (entry.isDirectory()) {
                    new File(filePath).mkdirs(); // 创建目录
                } else {
                    extractFile(zipIn, filePath); // 写入文件
                }
                zipIn.closeEntry();
            }
        }
    }*/
    // 2025/6/3 ai
    public void unzip(File zipFilePath, String destDir) throws Exception {
        try (ZipInputStream zipIn = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFilePath)))) {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {
                String filePath = destDir + File.separator + entry.getName();

                if (entry.isDirectory()) {
                    new File(filePath).mkdirs();
                } else {
                    // ✅ 提前创建父目录
                    File destFile = new File(filePath);
                    if (!destFile.getParentFile().exists()) {
                        destFile.getParentFile().mkdirs();
                    }

                    try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
                        byte[] buffer = new byte[4096];
                        int read;
                        while ((read = zipIn.read(buffer)) != -1) {
                            bos.write(buffer, 0, read);
                        }
                    }
                }
                zipIn.closeEntry();
            }
        }
    }

    private void extractFile(ZipInputStream zipIn, String filePath) throws IOException
    {
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath))) {
            byte[] buffer = new byte[4096];
            int read;
            while ((read = zipIn.read(buffer)) != -1) {
                bos.write(buffer, 0, read);
            }
        }
    }
    /**
     * 将文件内容读取为字符串
     *
     * @param file 要读取的文件对象
     * @return 文件内容的字符串表示
     * @throws IOException 如果读取文件时发生错误
     */
    public static String readFileToString(File file) throws IOException {
        // 使用 try-with-resources 确保资源自动关闭
        try (FileInputStream fis = new FileInputStream(file);
             InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
             BufferedReader reader = new BufferedReader(isr)) {

            StringBuilder content = new StringBuilder();
            String line;

            // 逐行读取文件内容
            while ((line = reader.readLine()) != null) {
                content.append(line).append(System.lineSeparator());
            }

            // 删除最后多余的行分隔符
            if (content.length() > 0) {
                content.setLength(content.length() - System.lineSeparator().length());
            }

            return content.toString();
        }
    }
}